// pages/shopcart/shopcart.js
import {Shopcart} from "../../models/shopcart.js"
import { Enum } from "../../utils/enum.js"
var shopcart = new Shopcart("buyLocalShopcart")

Page({
  
  /**
   * 页面的初始数据
   */
  data: {
    shopcart: {},
    storageKey: Enum.orderType.buyOrder
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._loadData()
  },

  _loadData(){
    var data = shopcart.getShopcartDetail(this.data.shopcart.selectedAll)
    this.setData({
      shopcart: data    
    })
  },

  onSelectAll(event){
    var data = shopcart.selectAll(!this.data.shopcart.selectedAll)
    this.setData({
      shopcart: data    
    })
  },

  onChangeNum(event) {
    var bookID = event.detail.bookID
    var changeType = event.detail.changeType * 1
    var result = shopcart.changeNum(bookID, changeType)
    if (result.ok){
      this.setData({
        shopcart: result.data
      })
    }
  },

  makeOrder(event){
    wx.setStorageSync(this.data.storageKey, this.data.shopcart)
    wx.navigateTo({
      url: "/pages/order/order?orderType=" + this.data.storageKey + "&shopcartType=" + shopcart.shopcartKey 
    })
  },

  onDeleteOne(event) {
    var bookID = event.detail.bookID
    var selectedAll = this.data.shopcart.selectedAll
    var result = shopcart.deleteOne(bookID, selectedAll)
    if (result.ok) {
      this.setData({
        shopcart: result.data
      })
    }
  },

  onSelect(event) {
    var data = shopcart.changeSelectStatus(event.detail.bookID)
    this.setData({
      shopcart: data    
    })
  }
})